package com.huwaiwai001.linked;


/**
 * 简单实现单向链表
 * Created by hww on 2018/9/25 下午7:56.
 */
public class MySinglyLinkedList<T> {

    /** 头结点 */
    private Node head = new Node();

    /** 尾结点 */
    private Node tail;

    /** 元素数量 */
    private int size = 0;

    public MySinglyLinkedList() {}


    public void add(T element) {
        if (element == null) {
            throw new NullPointerException("不能存null");
        }
        Node node = new Node(element);

        if (tail == null) {
            head.next = tail = node;
        } else {
            tail = tail.next = node;
        }
        size++;
    }

    public T get(int index) {
        if (index < 0 || index >= size) {
            throw new ArrayIndexOutOfBoundsException();
        }
        Node node = head;
        for (int i = 0; i <= index; i++) {
            node = node.next;
        }
        return (T) node.element;
    }

    /** 链表的元素 */
    private class Node<T> {

        private Node next;

        private T element;

        Node() {}

        Node(T element) {
            this.element = element;
        }

        boolean hasNext() {
            return next == null;
        }
    }



}
